package com.jintu.portal.service.datadriver.receiver;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.cache.RedisHelper;
import com.jintu.portal.mq.RabbitMqSender;
import com.jintu.portal.pojo.mq.NotificationEntity;
import com.jintu.portal.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;

/**
 * @author very
 */
@Slf4j
@Component
public class ReceiverCommonUtil {

    @Resource(name = "rabbitMqSender")
    private RabbitMqSender rabbitMqSender;

    @Resource(name = "redisHelper")
    private RedisHelper redisHelper;

    void changeFlagAndSendMq(JSONObject riskOrderInfo, JSONObject extDataJson){
        // 更改redis标记位为 1 - 以获取数据源，待清洗
        redisHelper.hset(CommonUtil.getDataSourceRedisKey(
                riskOrderInfo.getString("orderId"),
                riskOrderInfo.getInteger("userId")),
                riskOrderInfo.getString("dataSourceCode"),
                "1");// 1表示原始数据已经就位
        try {
            NotificationEntity sendingData = NotificationEntity.build(
                    riskOrderInfo.getInteger("userId"),
                    riskOrderInfo.getString("username"),
                    riskOrderInfo.getString("orderId"),
                    riskOrderInfo.getString("dataSourceCode"));
            JSONObject extData = new JSONObject();
            extData.put("type", riskOrderInfo.getString("dataSourceCode"));
            if(extDataJson != null && !extDataJson.isEmpty()){
                for(Map.Entry<String, Object> entry : extDataJson.entrySet()){
                    extData.put(entry.getKey(), entry.getValue());
                }
            }
            sendingData.setExt(extData);
            rabbitMqSender.sendMessage(sendingData);
        } catch (Exception e) {
            log.error("发送清洗MQ报错");
            log.error(e.getMessage(), e);
        }
        redisHelper.del(riskOrderInfo.getString("dataSourceCode") + "_" + riskOrderInfo.getString("orderId"));
    }

    String genDataRequestOrderId(String orderId) {
        Random ra = new Random();
        int ram = ra.nextInt(1000);
        return orderId + "-" + ram;
    }
}
